#include "curlclass.h"


size_t Curl::defaultCallback(void *buffer, size_t size, size_t nmemb, void *userp)
{
	int nTotal = size*nmemb;
	char* sBuf = new char[nTotal+1];
	memcpy(sBuf,buffer,nTotal);
	sBuf[nTotal] = 0;
	cout<<sBuf<<endl;
	return nTotal;
}

Curl::Curl()
{
	m_eErrCode = curl_global_init(CURL_GLOBAL_WIN32);
	
	m_pEasyHandle = curl_easy_init();
	m_eErrCode = curl_easy_setopt(m_pEasyHandle,CURLOPT_WRITEFUNCTION, defaultCallback);
	memset(m_sErrorBuff,0,CURL_ERROR_SIZE);
	m_eErrCode = curl_easy_setopt(m_pEasyHandle,CURLOPT_ERRORBUFFER, m_sErrorBuff);
	m_eErrCode = curl_easy_setopt(m_pEasyHandle,CURLOPT_VERBOSE,1);
	m_eErrCode.setFireException(true);
	if (!m_eErrCode)
	{
		throw giboException("Could not initialize Curl",m_eErrCode.getFirstError());
	}
}
string Curl::getError()
{
	return string(m_sErrorBuff);
}
void Curl::setUrl(string url)
{
	m_eErrCode = curl_easy_setopt(m_pEasyHandle,CURLOPT_URL,url.c_str());
}
void Curl::setCallback(size_t (*callback)(void*, size_t, size_t, void*))
{
	m_eErrCode = curl_easy_setopt(m_pEasyHandle,CURLOPT_WRITEFUNCTION, callback);
}
bool Curl::connect()
{

	return !curl_easy_perform(m_pEasyHandle);
}

bool Curl::setDirection(TransferDirection dir)
{
	if (dir == DOWNLOAD)
		m_eErrCode = curl_easy_setopt(m_pEasyHandle, CURLOPT_UPLOAD, 0L); 
	else
		m_eErrCode = curl_easy_setopt(m_pEasyHandle, CURLOPT_UPLOAD, 1L); 
	return !m_eErrCode;
}

//bool Curl::setType(TransferType type)
//{
//}

